/*  
 *  Copyright 2006 Paul Jack.
 *
 *  This file is part of the Dex compiler suite. 
 *  
 *  Dex is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *  
 *  Dex is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 *  Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */
package dex.compiler.checker;


import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import dex.compiler.checker.type.Type;
import dex.compiler.checker.type.TypeManager;
import dex.compiler.model.definition.Callable;
import dex.compiler.model.definition.Definition;
import dex.compiler.model.definition.TypedName;
import dex.compiler.model.definition.Unit;
import dex.compiler.model.program.NameSearcher;


/**
 * Searches for functions.
 */
public class FunctionSearcher extends NameSearcher {

	//FIXME: Find a better home for this.
	
	/**
	 * The argument types to search for.
	 */
	final private Collection<Type> arguments;
	
	
	/**
	 * The manager used to convert type nodes to types.
	 */
	final private TypeManager manager;


	/**
	 * Constructs a new function searcher.
	 * 
	 * @param manager  the type manager used to convert type nodes to types
	 * @param name     the name of the function to search for
	 * @param arguments  the parameter types of the function to search for
	 */
	public FunctionSearcher(Class<? extends Callable> cls, TypeManager manager, String name, Collection<Type> arguments) {
		super(cls, name);
		this.arguments = arguments;
		this.manager = manager;
	}
	
	
	@Override
	public boolean matches(Unit unit, Definition d) {
		if (!super.matches(unit, d)) {
			return false;
		}
		Callable function = (Callable)d;
		List<TypedName> parameters = function.getParameters();
		if (parameters.size() != arguments.size()) {
			return false;
		}
		Iterator<Type> iter = arguments.iterator();
		for (int i = 0; i < parameters.size(); i++) {
			Type formal = manager.toType(unit, parameters.get(i).getType());
			Type actual = iter.next();
			if (!actual.canAssignTo(formal)) {
				return false;
			}
		}
		return true;
	}


}
